package com.cn.wanxi.servlet;

import com.cn.wanxi.model.NewsModel;
import com.cn.wanxi.service.NewsService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/UpdateNewsServlet")
public class UpdateNewsServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        在之前，我们需要对编码进行统一，否则有可能是乱码
//        只要通过前台页面向后台传递的值有中文的情况下，都要去做一些乱码统一
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//1.得到页面传递过来的值
        String idstring = req.getParameter("id");
        int id = idstring == null || "".equals(idstring) ? 0 : Integer.parseInt(idstring);
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        String isTuijianStr = req.getParameter("isTuijian");
        String isTopStr = req.getParameter("isTop");

//        2.封装model
        NewsModel newsModel = new NewsModel();
        newsModel.setId(id);
        newsModel.setTitle(title);
        newsModel.setContent(content);
        newsModel.setIsTuijian("是".equals(isTuijianStr) ? 1 : 0);
        newsModel.setIsTop("on".equals(isTopStr) ? 1 : 0);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        if (id == 0) {
            newsModel.setCreateTime(simpleDateFormat.format(new Date()));
        }
        newsModel.setUpdateTime(simpleDateFormat.format(new Date()));
//        3.调用逻辑层service
        NewsService newsService = new NewsService();
//        判断id是否有值，如果有值，则表示编辑修改，如果没有值则表示新增
        if (id == 0) {
            newsService.add(newsModel);
        } else {
            newsService.update(newsModel);
        }
//        4.跳转页面,到查询页面
        resp.sendRedirect("newsPage");
    }
}
